"""
【共享】
享元模式(Flyweight Pattern): 允许将对象共享以节省内存和提高性能。Python 中，可使用缓存实现享元模式。
"""


class Flyweight:
    def __init__(self, shared_state):
        self._shared_state = shared_state

    def operation(self, unique_state):
        s = f"shared ({self._shared_state}) and unique ({unique_state})"
        print(s)


class FlyweightFactory:
    _flyweights = {}

    def get_flyweight(self, shared_state):
        if shared_state not in self._flyweights:
            self._flyweights[shared_state] = Flyweight(
                shared_state)
        return self._flyweights[shared_state]


factory = FlyweightFactory()
flyweight1 = factory.get_flyweight("state1")
flyweight2 = factory.get_flyweight("state1")
flyweight3 = factory.get_flyweight("state2")
flyweight4 = factory.get_flyweight("state2")

flyweight1.operation("unique1")
flyweight2.operation("unique2")
flyweight3.operation("unique3")
flyweight4.operation("unique4")
"""
shared (state1) and unique (unique1)
shared (state1) and unique (unique2)
shared (state2) and unique (unique3)
shared (state2) and unique (unique4)
"""
